package com.djf.controller;

import com.djf.service.FlowableService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试控制器
 * 提供简单的测试接口来验证Flowable功能
 * 
 * @author djf
 * @date 2025/01/20
 */
@Slf4j
@RestController
@RequestMapping("/api/test")
@CrossOrigin(origins = "*")
public class TestController {

    @Autowired
    private FlowableService flowableService;

    /**
     * 健康检查接口
     * 
     * @return 健康状态
     */
    @GetMapping("/health")
    public Map<String, Object> health() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("service", "djf-flowable");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }

    /**
     * 快速测试请假流程
     * 
     * @return 测试结果
     */
    @PostMapping("/quick-leave-test")
    public Map<String, Object> quickLeaveTest() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 准备流程变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("leaveType", "annual");
            variables.put("startDate", "2025-02-01");
            variables.put("endDate", "2025-02-03");
            variables.put("leaveDays", 3L);
            variables.put("reason", "春节回家过年");
            variables.put("emergencyContact", "张三 13800138000");
            
            // 启动流程
            String processInstanceId = flowableService.startProcess(
                    "leaveApproval", 
                    "LEAVE_" + System.currentTimeMillis(), 
                    variables, 
                    "employee001"
            );
            
            result.put("success", true);
            result.put("processInstanceId", processInstanceId);
            result.put("message", "请假流程启动成功");
            result.put("variables", variables);
            
            log.info("快速测试请假流程启动成功，流程实例ID: {}", processInstanceId);
            
        } catch (Exception e) {
            log.error("快速测试请假流程失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "测试失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 模拟完成填写请假申请任务
     * 
     * @param processInstanceId 流程实例ID
     * @return 完成结果
     */
    @PostMapping("/complete-leave-application/{processInstanceId}")
    public Map<String, Object> completeLeaveApplication(@PathVariable String processInstanceId) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 查找当前任务
            List<Task> tasks = flowableService.getTodoTasks("employee001");
            if (tasks.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到待办任务");
                return result;
            }
            
            String taskId = tasks.get(0).getId();
            
            // 准备任务变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("leaveType", "annual");
            variables.put("startDate", "2025-02-01");
            variables.put("endDate", "2025-02-03");
            variables.put("leaveDays", 3L);
            variables.put("reason", "春节回家过年");
            variables.put("emergencyContact", "张三 13800138000");
            
            // 完成任务
            flowableService.completeTask(taskId, variables, "请假申请已填写完成", "employee001");
            
            result.put("success", true);
            result.put("taskId", taskId);
            result.put("message", "请假申请填写完成");
            
        } catch (Exception e) {
            log.error("完成请假申请失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "完成任务失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 模拟领导审批
     * 
     * @param approve 是否同意
     * @return 审批结果
     */
    @PostMapping("/manager-approval")
    public Map<String, Object> managerApproval(@RequestParam(defaultValue = "true") boolean approve) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 查找领导待办任务
            List<Task>  tasks = flowableService.getCandidateTasks("manager001");
            if (tasks.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到领导待审批任务");
                return result;
            }
            
            String taskId = tasks.get(0).getId();
            
            // 先认领任务
            flowableService.claimTask(taskId, "manager001");
            
            // 准备审批变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("managerApproval", approve ? "approve" : "reject");
            variables.put("managerComment", approve ? "同意请假，注意安全" : "工作繁忙，暂不批准请假");
            
            // 完成审批
            flowableService.completeTask(taskId, variables, 
                    approve ? "领导审批通过" : "领导审批拒绝", "manager001");
            
            result.put("success", true);
            result.put("taskId", taskId);
            result.put("approval", approve);
            result.put("message", approve ? "领导审批通过" : "领导审批拒绝");
            
        } catch (Exception e) {
            log.error("领导审批失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "审批失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 模拟HR审批（针对长假期）
     * 
     * @param approve 是否同意
     * @return 审批结果
     */
    @PostMapping("/hr-approval")
    public Map<String, Object> hrApproval(@RequestParam(defaultValue = "true") boolean approve) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 查找HR待办任务
            List<Task>  tasks = flowableService.getCandidateTasks("hr001");
            if (tasks.isEmpty()) {
                result.put("success", false);
                result.put("message", "未找到HR待审批任务");
                return result;
            }
            
            String taskId = tasks.get(0).getId();
            
            // 先认领任务
            flowableService.claimTask(taskId, "hr001");
            
            // 准备审批变量
            Map<String, Object> variables = new HashMap<>();
            variables.put("hrApproval", approve ? "approve" : "reject");
            variables.put("hrComment", approve ? "HR审批通过，祝假期愉快" : "请假时间过长，建议调整");
            
            // 完成审批
            flowableService.completeTask(taskId, variables, 
                    approve ? "HR审批通过" : "HR审批拒绝", "hr001");
            
            result.put("success", true);
            result.put("taskId", taskId);
            result.put("approval", approve);
            result.put("message", approve ? "HR审批通过" : "HR审批拒绝");
            
        } catch (Exception e) {
            log.error("HR审批失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "HR审批失败: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取系统信息
     * 
     * @return 系统信息
     */
    @GetMapping("/system-info")
    public Map<String, Object> getSystemInfo() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取流程定义数量
            List<ProcessDefinition> processDefinitions = flowableService.getProcessDefinitions();
            result.put("success", true);
            result.put("processDefinitionCount", processDefinitions.size());
            result.put("javaVersion", System.getProperty("java.version"));
            result.put("osName", System.getProperty("os.name"));
            result.put("availableProcessors", Runtime.getRuntime().availableProcessors());
            result.put("maxMemory", Runtime.getRuntime().maxMemory() / 1024 / 1024 + "MB");
            result.put("totalMemory", Runtime.getRuntime().totalMemory() / 1024 / 1024 + "MB");
            result.put("freeMemory", Runtime.getRuntime().freeMemory() / 1024 / 1024 + "MB");
            
        } catch (Exception e) {
            log.error("获取系统信息失败: {}", e.getMessage(), e);
            result.put("success", false);
            result.put("message", "获取系统信息失败: " + e.getMessage());
        }
        
        return result;
    }
}